unit SyncNodeMainUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, SyncNodeUnit, IdBaseComponent, IdAntiFreezeBase, IdAntiFreeze,
  ADODB, DB,
  TcpFileClient, CoolTrayIcon, StdCtrls, Menus, ComCtrls, ExtCtrls, Gauges,
  AppEvnts, SUISkinEngine,
  IniFiles, Registry;

type
  TfrmSyncNode = class(TForm)
    IdAntiFreeze1: TIdAntiFreeze;
    TI: TCoolTrayIcon;
    lblSoftwareName: TLabel;
    lblStatus: TLabel;
    Timer1: TTimer;
    pbView: TGauge;
    ApplicationEvents1: TApplicationEvents;
    SE: TsuiSkinEngine;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure ApplicationEvents1Exception(Sender: TObject; E: Exception);
  private
    { Private declarations }
    FSyncNode: TSyncNode;
    FAbort: Boolean;
    FTcpCli: TTcpCompareClient;
    FHost, FLocalIp: string;
    FPort: Integer;
    procedure DoBatchUpdate;
    procedure OnTcpEvent(AStatus: string; AAllSize,
                         ACurSize, AFileAllSize, AFileCurSize: Int64; ASpeed: Double;
                         ARemainTime: TDateTime);
    procedure ShowWindow;
    procedure HideWindow;
  public
    { Public declarations }
  end;

var
  frmSyncNode: TfrmSyncNode;

implementation

uses ConstUnit, FunctionUnit, VDUnit, {DllImportUnit, }ChooseIpUnit,
  SyncNodeUtil;

{$R *.dfm}

procedure TfrmSyncNode.DoBatchUpdate;
var
  Database: TADOConnection;
  Query: TADOQuery;
  ClientDriver, Sql, ClientPath: string;
  SL: TStrings;

  procedure LoadClientGroup;
  var
    Sql, ComputerName, s: string;
    Query: TADOQuery;
    SL: TStrings;
  begin
//    ComputerName := GetLocalComputerName;
//
//    Sql := Format('SELECT g.* FROM Groups as g Left JOIN ' +
//                  ' ComputerGroup AS cg ON cg.GroupId = g.GroupId WHERE cg.ComputerName = "%s"', [ComputerName]);
//    Query := TADOQuery.Create( nil );
//    try
//      OpenDataSet(Sql, Query, Database);
//      if Query.IsEmpty then
//        Exit;
    SL := TStringList.Create;
    try
      s := '';
      s := TrackGet(GetSysParams(ServerIps, Database));
      if (s = '') or (s = 'null') or (Length(s) > 255) then
      begin
        FHost := GetSysParams(ServerIps, Database);
        FPort := TcpFilePort;
      end
      else
      begin
        ParseLine(s, ':', SL);
        if SL.Count <> 2 then
          Exit;
        FHost := SL[0];
        FPort := StrToIntDef(SL[1], TcpFilePort);
      end;
    finally
      SL.Free;
    end;
//      Query.FieldByName('TcpFileHost').AsString;
//      Query.FieldByName('TcpFilePort').AsInteger;
//      FVNDHost := Query.FieldByName('VDiskIp').AsString;
//      FVNDPort := Query.FieldByName('VDiskPort').AsString;
//      FHost := GetSysParams(ServerIps, Database);
//      FPort := TcpFilePort;
//      if FPort = 0 then

//    finally
//      Free;
//    end;
//    finally
//      Query.Free;
//    end;
  end;
begin
  Database := TADOConnection.Create(Self);
  SL := TStringList.Create;
  try
    Database.ConnectionString := Format(DBFormat, [ExtractFilePath(ParamStr(0)) + 'Data\BarData.mdb']);
    ClientDriver := GetSysParams(WtRestoreOption, Database);
    if ClientDriver = '' then
      ClientDriver := 'D';
    LoadClientGroup;
//    Mount9Disk;
    Query := TADOQuery.Create(nil);
    OpenDataSet( Format('SELECT * FROM Software WHERE SoftwareUpdateMode = %d', [Integer(smTcp)]), Query, Database );
//    Query.Connection := Database;
//    Query.Open;

    ShowWindow;
    Caption := 'Game updating...';
    while not Query.Eof do
    begin
//      SL.Add(Format('%s|%s', [Query.FieldByName]))
//      Query.Next;
//    end;
      if FAbort then
        Break;
      lblSoftwareName.Caption := Format('Updating[%s]', [ Query.FieldByName('SoftwareName').AsString ]);
//      if fcGetProtection then
//        ClientPath := '1' + Copy(Query.FieldByName('SoftwareServerPath').AsString, 2, Length(Query.FieldByName('SoftwareServerPath').AsString))
//      else
//        ClientPath := 'D' + Copy(Query.FieldByName('SoftwareServerPath').AsString, 2, Length(Query.FieldByName('SoftwareServerPath').AsString));
      ClientPath := ClientDriver + Copy(Query.FieldByName('SoftwareServerPath').AsString, 2, Length(Query.FieldByName('SoftwareServerPath').AsString));

      FTcpCli := TTcpCompareClient.Create(Query.FieldByName('SoftwareServerPath').AsString,
                                          ClientPath,
                                          FHost, FPort,
                                          Query.FieldByName('SoftwareIndexFile').AsString,
                                          IncludeTrailingPathDelimiter(ClientPath) + ExtractFileName(Query.FieldByName('SoftwareIndexFile').AsString),
                                          False, False, True);
      try
        FTcpCli.OnCompareCopyEvent := OnTcpEvent;
        FTcpCli.DoStart;  
      finally
        FTcpCli.Free;
      end;     
      Query.Next;
    end;
    Query.Free;

    HideWindow;
    
//    RefreshVD;
//    Unmount9Disk;


    FSyncNode := TSyncNode.Create(GetSysParams(ServerIps, Database), TcpFilePort, FLocalIp);
    FSyncNode.Start;
    Timer1Timer(Timer1);

  finally
    Database.Free;
    SL.Free;
  end;

end;

procedure TfrmSyncNode.FormCreate(Sender: TObject);
var
  SL: TStrings;
  fChooseIp: TfrmChooseIp;
begin
//  SL := TStringList.Create;
//  try
//  with TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini') do
  KillTrayIcons;
  with TRegistry.Create do
  try
    RootKey := HKEY_LOCAL_MACHINE;
    OpenKey(WtManageRegistry, True);
    FLocalIp := ReadString('HostIp');//ReadString('SyncNodeIp', 'Ip', '');
    if FLocalIp = '' then
    begin
      fChooseIp := TfrmChooseIp.Create(Application);
      SE.AddForm(fChooseIp);
      with fChooseIp do
      try
        if cbbIps.Items.Count > 1 then
          if ShowModal = IdOK then
          begin

            FLocalIp := cbbIps.Text;
          end;

        WriteString('HostIp', FLocalIp);
      finally
        fChooseIp.Free;
      end;
    end;
  finally
    Free;
  end;

  DoBatchUpdate;
end;

procedure TfrmSyncNode.FormDestroy(Sender: TObject);
begin
  if Assigned(FSyncNode) then
    FSyncNode.Free;
end;

procedure TfrmSyncNode.HideWindow;
begin
  AnimateWindow(Self.Handle, 800, AW_BLEND or AW_HIDE);
//  Hide;
end;

procedure TfrmSyncNode.OnTcpEvent(AStatus: string; AAllSize, ACurSize,
  AFileAllSize, AFileCurSize: Int64; ASpeed: Double;
  ARemainTime: TDateTime);
begin
  if FAbort then
    Exit;
  FormStyle := fsStayOnTop;
  pbView.MaxValue := AAllSize div 1024;
  pbView.MinValue := 0;
  pbView.Progress := ACurSize div 1024;
  lblStatus.Caption := AStatus + Format('  %.2f M/S', [ASpeed / 1024 / 1024]) + ' Left Time: ' + FormatDateTime('HH:MM:SS', ARemainTime);
end;

procedure TfrmSyncNode.ShowWindow;
begin
  Left := Screen.WorkAreaWidth - Width;
  Top := Screen.WorkAreaHeight - Height;
  AnimateWindow(Self.Handle, 800, AW_BLEND or AW_ACTIVATE)
//  Show;
end;

procedure TfrmSyncNode.Timer1Timer(Sender: TObject);
begin
  if not Assigned( FSyncNode ) then
    Exit;
  Caption := Format('Sub Server -  Ip: %s, Port: %d, Clients: %d',
                    [ FSyncNode.BindingIps, FSyncNode.FilePort, FSyncNode.ClientCount]);

  TI.Hint := Caption;
end;

procedure TfrmSyncNode.ApplicationEvents1Exception(Sender: TObject;
  E: Exception);
begin
//
  LogMessage(Format('WtSyncNode - %s, %s', [E.ClassName, E.Message]));
end;

end.
